# TCP server example
import socket

DEFAULT_SOCKET_NUMBER = 6690

class remote_server(Thread):
    _server_socket = None
    _bIsRunning = False
    _bStopThread = False

   def __init__(self):
        _server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        _server_socket.bind(("", DEFAULT_SOCKET_NUMBER))
        _server_socket.listen(0)
        print "TCPServer Waiting for client on port " + DEFAULT_SOCKET_NUMBER


    def run(self):
        # Check to see that we're not already connected to the client
        if( not self.isRunning()):
            # Accept connection, and start....
            self._bIsRunning = True
            while not self._bStopThread:
                client_socket, address = server_socket.accept()
                print "(II) Got a connection from ", address
                socket_closed = False
                while not (socket_closed or self._bStopThread):
                    data = client_socket.recv(512)
                    print "(II) RECIEVED:" , data

                    # 1= GET_DISPLAYS
                    if data[0:1] == '1':
                        print "(II) Sent reply"
                        client_socket.send ("LEN|CRT-1\n")

                    # 2 = SET_DISPLAYS
                    elif data[0:1] == '2':
                        print "(II) Request for setting up screens: " + data[1:]

                    # 3 = CLOSE_CONNECTION
                    elif data[0:1] == '3':
                        client_socket.close
                        print "(II) Closing socket"
                        socket_closed=True
        else:
            print "Connection to client already established"

    # Stop and kill the thread
    def stop(self):
        self._bStopThread = True

    def __del__(self):
        if( self._server_socket != None):
            self.stop()
            self._server_socket.close()
            self._server_socket = None

    # Returns a string with displayID:s separated by "|"
    def _getDisplays(self):
        test = MyDisplays()
        lstDisplays =  test.getDisplays()
        sReturnText = ""
        if len(lstDisplays) == 1:
            sReturnText = lstDisplays[0].getID()
        else:
            for disp in lstDisplays:
                if(sReturnText != ""):
                    sReturnText = sReturnText + "|"
                sReturnText = sReturnText + disp.getID()

        return sReturnText


    def _apply_setup(self, p_sSetupString):
        tokens = p_sSetupString.split("|") # Tokenize på "|"
        if(len(tokens) == 2):
            cmd = ["--single","-d " + tokens[1]]
        elif(len(tokens) == 3:
            cmd = ["--extend","--direction=right","-d " + tokens[1] + "," + tokens[2]]
        elif:
            print "(EE) Got a wrong number of screens!"



        # Try to apply the configuration!
        try:
            print "(II) Apply configuration: " + cmd
            #popen = subprocess.Popen(['disper'] + cmd, stderr=subprocess.PIPE)
        except OSError, e:
            report(_('Failed to run disper utility:\n\n%s') % e.strerror)
        else:
            #error_code = popen.wait()
            if error_code != 0:
                report(_('Disper program terminated with error code %d:\n\n%s') %
                    (error_code, popen.stderr.read()))


